﻿using ChuanYe.CountyFireManagement.EF.MySQL.Models;
using ChuanYe.CountyFireManagement.Model;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChuanYe.CountyFireManagement.BLL
{
    public class FireStationBLL
    {
        #region 构造单例
        private FireStationBLL() { }
        private static FireStationBLL _instance;
        public static FireStationBLL Instance
        {
            get
            {
                return _instance ?? (_instance = new FireStationBLL());
            }
        }
        #endregion

        public ResultDto<List<FireMQTTResponseModel>> Complete(int fireId, int sceneUserId, bool isReburn, DateTime? sceneTime, string ip, 
                                                                     string reviseLatitude, string reviseLongitude, string reviseAltitude, List<Firestationattach> firestationattachs)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var fireInfo = ef.Fireinfo.Where(p => p.FireId == fireId).FirstOrDefault();
                if (fireInfo == null)
                {
                    result.Status = -1;
                    result.Message = "FireInfo Is Not Exist";
                    return result;
                }

                var exist = ef.Firestation.Where(p => p.FireId == fireId && p.SceneUserId == sceneUserId).FirstOrDefault();
                if (exist == null)
                {
                    result.Status = -2;
                    result.Message = "Firestation Is No Begining";
                    return result;
                }
                exist.SceneTime = sceneTime ?? DateTime.Now;
                exist.IsReburn = isReburn == false ? 0 : 1;
                exist.ReviseLatitude = reviseLatitude;
                exist.ReviseLongitude = reviseLongitude;
                exist.ReviseAltitude = reviseAltitude;
                ef.Firestation.Add(exist);
                ef.Entry<Firestation>(exist).State = EntityState.Modified;


                //增加驻守附件
                foreach (var item in firestationattachs)
                {
                    item.StationId = exist.StationId;
                    ef.Firestationattach.Add(item);
                    ef.Entry<Firestationattach>(item).State = EntityState.Added;
                    ef.SaveChanges();
                }

                var userInfo = ef.Userinfo.Where(p => p.UserId == sceneUserId).FirstOrDefault();

                Record record = new Record();
                record.FireId = exist.FireId;
                record.HandleTime = DateTime.Now;
                record.Type = (int)RecordType.复燃核实;
                record.UserId = sceneUserId;
                record.Content =  fireInfo.FireName + (exist.IsReburn == 1 ? "出现复燃情况" : "无复燃情况");
                record.AddTime = record.HandleTime;
                record.Ip = ip;
                record.Applicant = userInfo.AccountName;

                record.CustomData = exist.StationId.ToString();
                ef.Record.Add(record);
                ef.Entry<Record>(record).State = EntityState.Added;

                //消息
                Message message = new Message();
                message.FireId = fireInfo.FireId;
                message.Type = (int)MessageType.复燃核实;
                message.Content = record.Content;
                message.SendType = (int)MessageSendType.用户对用户发送;
                message.IsRead = 0;
                message.HandleTime = exist.TransDatetime;
                message.SendUserId = exist.UserId;
                message.Ip = fireInfo.Ip;
                ef.Message.Add(message);
                ef.Entry<Message>(message).State = EntityState.Added;

                if (isReburn)
                {
                    //移除终报倒计时
                    var tempRT = (int)RecordType.终报未按时操作;
                    var existFireexpire = ef.Fireexpire.Where(p => p.FireId == fireInfo.FireId && p.RecordType == tempRT).FirstOrDefault();
                    if (existFireexpire == null)
                    {
                        ef.Fireexpire.Add(existFireexpire);
                        ef.Entry<Fireexpire>(existFireexpire).State = EntityState.Deleted;
                    }
                }
                ef.SaveChanges();

                #region 装载消息
                List<Message> messages = new List<Message>() { message };
                result.FirstParam = MessageBLL.Instance.TransMessageToFireMQTTResponseModel(messages, record.Type.Value);
                #endregion
                return result;
            }
        }

        public ResultDto<List<FireMQTTResponseModel>> Add(Firestation firestation, Firesite firesite)
        {
            ResultDto<List<FireMQTTResponseModel>> result = new ResultDto<List<FireMQTTResponseModel>>();
            using (CountyFireManagementContext ef = new CountyFireManagementContext())
            {
                var fireInfo = ef.Fireinfo.Where(p => p.FireId == firestation.FireId).FirstOrDefault();
                if (fireInfo == null)
                {
                    result.Status = -1;
                    result.Message = "FireInfo Is Not Exist";
                    return result;
                }
                string happenDatetime = firestation.TransDatetime.ToString("yyyy-MM-dd HH:mm:ss");
                firestation.RecordType = (int)RecordType.驻守调动;
                firestation.SendStatus = 0;
                firestation.IsReburn = 0;
                ef.Firestation.Add(firestation);
                ef.Entry<Firestation>(firestation).State = EntityState.Added;
                var userInfo = ef.Userinfo.Where(p => p.UserId == firestation.SceneUserId).FirstOrDefault();
                if (userInfo != null)
                {
                    if (firesite.FireId.HasValue && firesite.FireId.Value > 0
                             && !string.IsNullOrEmpty(firesite.Latitude) && !string.IsNullOrEmpty(firesite.Longitude))
                    {
                        //坐标地址转换
                        string[] longitudeSplit = firesite.Longitude.Split('|');
                        string longitudeString = longitudeSplit[0] + "度" + longitudeSplit[1] + "分" + longitudeSplit[2] + "秒";
                        string[] latitudeSplit = firesite.Latitude.Split('|');
                        string latitudeString = latitudeSplit[0] + "度" + latitudeSplit[1] + "分" + latitudeSplit[2] + "秒";
                        firesite.Content = $"{userInfo.RealName}前往 经度:{longitudeString}(预计)，纬度:{latitudeString}(预计)，执行驻守任务";
                        firesite.RecordType = firestation.RecordType;
                        ef.Firesite.Add(firesite);
                        ef.Entry<Firesite>(firesite).State = EntityState.Added;
                    }
                    ef.SaveChanges();

                    Record record = new Record();
                    record.FireId = fireInfo.FireId;
                    record.HandleTime = firestation.TransDatetime;
                    record.Type = (int)RecordType.驻守调动;
                    record.UserId = firestation.UserId;
                    record.Content = string.Format(FireInfoTool.GetFireInfoRecordFormat((int)record.Type), fireInfo.FireName, happenDatetime, userInfo.RealName, userInfo.Phone);
                    record.AddTime = firestation.TransDatetime;
                    record.Ip = firestation.Ip;
                    record.Applicant = fireInfo.Alarm;
                    record.CustomData = firestation.StationId.ToString();
                    ef.Record.Add(record);
                    ef.Entry<Record>(record).State = EntityState.Added;
                    ef.SaveChanges();


                    Message message = new Message();
                    message.FireId = fireInfo.FireId;
                    message.Type = (int)MessageType.驻守调动;
                    message.Content = string.Format(FireInfoTool.GetFireInfoMessageFormat(message.Type), fireInfo.FireName, userInfo.RealName, userInfo.Phone);
                    message.SendType = (int)MessageSendType.用户对用户发送;
                    message.IsRead = 0;
                    message.HandleTime = fireInfo.HappenDatetime;
                    message.SendUserId = firestation.UserId;
                    message.TargetUserId = firestation.SceneUserId;
                    message.Ip = fireInfo.Ip;
                    ef.Message.Add(message);
                    ef.Entry<Message>(message).State = EntityState.Added;
                    ef.SaveChanges();
                    #region 装载消息
                    List<Message> messages = new List<Message>() { message };
                    result.FirstParam = MessageBLL.Instance.TransMessageToFireMQTTResponseModel(messages, (int)record.Type);
                    #endregion
                }

                var tempRT=(int)RecordType.终报未按时操作;
                var existFireexpire = ef.Fireexpire.Where(p => p.FireId == fireInfo.FireId && p.RecordType == tempRT).FirstOrDefault();
                if (existFireexpire != null)
                {
                    existFireexpire.StartTime = firestation.TransDatetime;
                    existFireexpire.Value = 24 * 60;
                    ef.Fireexpire.Add(existFireexpire);
                    ef.Entry<Fireexpire>(existFireexpire).State = EntityState.Modified;
                }
                ef.SaveChanges();
                return result;
            }
        }
    }
}
